package com.immediatus.engine.modifier;

import com.immediatus.contracts.IUpdateHandler;
import com.immediatus.engine.contracts.IModifier;
import com.immediatus.util.SmartList;

import java.util.ArrayList;

public class ModifierList<T> extends SmartList<IModifier<T>> implements IUpdateHandler{
    private final T _target;

    public ModifierList(final T target_){
        this._target = target_;
    }

    public ModifierList(final T target_, final int capacity_){
        super(capacity_);
        this._target = target_;
    }

    public T getTarget(){
        return this._target;
    }

    @Override
    public void onUpdate(final float secondsElapsed_){
        final ArrayList<IModifier<T>> modifiers = this;
        final int modifierCount = this.size();
        if (modifierCount > 0){
            for (int i = modifierCount - 1; i >= 0; i--){
                final IModifier<T> modifier = modifiers.get(i);
                modifier.onUpdate(secondsElapsed_, this._target);
                if (modifier.isFinished() && modifier.isRemoveWhenFinished()){
                    modifiers.remove(i);
                }
            }
        }
    }

    @Override
    public void reset(){
        final ArrayList<IModifier<T>> modifiers = this;
        for (int i = modifiers.size() - 1; i >= 0; i--){
            modifiers.get(i).reset();
        }
    }
}
